package com.sphd.emanu.activity.goodstype;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.github.yoojia.inputs.AndroidNextInputs;
import com.github.yoojia.inputs.StaticScheme;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.sphd.emanu.R;
import com.sphd.emanu.activity.goodslist.GoodslistActivity;
import com.sphd.emanu.adapter.GoodstypeAdapter;
import com.sphd.emanu.config.Constant;
import com.sphd.emanu.mvp.MVPBaseActivity;
import com.sphd.emanu.permission.Moudle;
import com.sphd.emanu.pojo.goods.Category;
import com.sphd.emanu.pojo.login.User;
import com.sphd.emanu.utils.PermissionConfig;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;


/**
 * 商品分类界面
 *
 * @Author Hu
 * @Time 2017/4/11 -- 17:03.
 * @Email 87683202@qq.com
 */
public class GoodstypeActivity extends MVPBaseActivity<GoodstypeContract.View, GoodstypePresenter> implements GoodstypeContract.View {
    @BindView(R.id.add_type)
    TextView addType;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.my_recycler)
    RecyclerView myRecycler;
    @BindView(R.id.my_swf)
    SwipeRefreshLayout mySwf;
    GoodstypeAdapter goodstypeAdapter;
    Intent intent;
    Bundle bundle;
    User userEntity;
    List<Moudle> moudles;
    boolean isCanDo=false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goodstype);
        ButterKnife.bind(this);
        initView();
        initEvent();
    }

    private void initEvent() {
        toolbar.setNavigationOnClickListener(v -> finish());
        myRecycler.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                bundle.putSerializable(Constant.LIST_CATEGORY, (Serializable) adapter.getData());
                bundle.putSerializable(Constant.CATEGORY, (Serializable) adapter.getItem(position));
                bundle.putInt(Constant.POS,position);
                intent.putExtras(bundle);
                intent.setClass(context, GoodslistActivity.class);
                startActivity(intent);
            }

            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                super.onItemChildClick(adapter, view, position);
                Category category = (Category) adapter.getItem(position);
                addAndEdit("请输入分类名称", category.getName(),2,category.getId());
            }

            @Override
            public void onItemLongClick(final BaseQuickAdapter adapter, View view, final int position) {
                super.onItemLongClick(adapter, view, position);
                new SweetAlertDialog(context,SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("删除").setContentText("确定要删除"+((Category)(adapter.getItem(position))).getName()+"分类吗？")
                        .setConfirmText("确定").setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        showProgressDialog();
                        mPresenter.deleteCategory(((Category)(adapter.getItem(position))).getId(),sweetAlertDialog);
                    }
                }).setCancelText("取消").setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                            sweetAlertDialog.dismiss();
                    }
                }).show();
            }
        });
        mySwf.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                addData();
            }
        });
    }

    private void initView() {
        setTitleBar(toolbar, "商品分类");
        initAdapter();
        setRefresh(mySwf);
        intent = getIntent();
        bundle = intent.getExtras();
        userEntity = (User) bundle.getSerializable(Constant.USER_ENTITY);
        moudles= (List<Moudle>) bundle.getSerializable(Constant.PERMISSION_LIST);
        isCanDo=isCanDo(moudles, PermissionConfig.MENU_FOOD_1);
        if (isCanDo){
            addType.setVisibility(View.VISIBLE);
        }
        addData();

    }

    private void addData() {
        mPresenter.getList(userEntity.getOid());
        showProgressDialog();
    }

    private void initAdapter() {
        setRecy(myRecycler);
        goodstypeAdapter = new GoodstypeAdapter(R.layout.item_goods_type, new ArrayList<Category>(),isCanDo);
        goodstypeAdapter.setEmptyView(emptyView);
        myRecycler.setAdapter(goodstypeAdapter);
    }

    @Override
    public void setObject(List<Category>  catelist) {
        dissProgressDialog();
        goodstypeAdapter.setNewData(catelist);
    }

    @OnClick(R.id.add_type)
    public void onViewClicked() {
        addAndEdit("请输入分类名称", "",1,0);
    }

    /**
     * @param title
     * @param classfy
     * @param type 1为增加 2为修改
     */
    private void addAndEdit(String title, String classfy, final int type, final int id) {
        View view = View.inflate(context, R.layout.dialog_edit, null);
        final MaterialEditText materialEditText = (MaterialEditText) view.findViewById(R.id.my_edit);
        if (TextUtils.isEmpty(classfy)) {
            materialEditText.setHint("分类名称");
        } else {
            materialEditText.setText(classfy);
        }
        final AlertDialog alertDialog = getDialogBuilder(view, title, "确定", "取消");
        final AndroidNextInputs androidNextInputs = new AndroidNextInputs();
        androidNextInputs.add(materialEditText, StaticScheme.Required().msgOnFail("请输入分类名称"), StaticScheme.NotBlank().msgOnFail("分类名称不能为空"));
       alertDialog.show();
        alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (androidNextInputs.test()) {
                    showProgressDialog();
                    if (type==1){
                    mPresenter.addCategory(materialEditText.getText().toString(), 1, alertDialog);
                    }else {
                    mPresenter.updateCategory(id,materialEditText.getText().toString(), 1, alertDialog);
                    }
                } else {
                    return;
                }

            }
        });
    }

    @Override
    public void setRes(int res, AlertDialog alertDialog) {
        dissProgressDialog();
        if (res == 1) {
            alertDialog.dismiss();
            addData();
        } else {
            toast("新增分类失败，请重试。");
        }
    }

    @Override
    public void setDelRes(int res, SweetAlertDialog alertDialog) {
        if (res == 1) {
            alertDialog.dismiss();
            addData();
        } else {
            toast("删除分类失败，请重试。");
        }
    }
}
